<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;

/**
 * 首页接口
 */
class Index extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 首页
     *
     */
    public function index()
    {
        $this->success('请求成功');
    }


    /**
     * 保存用户数据,归档流水
     */
    public function save_user()
    {
        //$data = Db::name("vip_orders")->group("username")->count();
        //dump($data);die;
        ini_set("memory_limit","800M");
        set_time_limit(0);

        $time = time();
        //$month = date("Y-m",$time);
        // 查询未导入的用户流水
        $data = Db::name("vip_orders")->field("*,SUM(money) AS sum_money")->where("status",0)->group("username,savetime")->limit(0,1000)->select();
        //dump($data);die;
        //$data2 = Db::name("vip_orders")->where("status",0)->limit(0,1000)->select();
        $description = Db::name("vip_description")->order("save_money desc")->cache(true)->select();//奖金
        if(empty($data)){
            return json(["status"=>200,"msg"=>"无归档数据"]);
        }
        $month = date("Y-m",$data[0]['savetime']);
        //$ids = [];
        //$ids = array_column($data2,"id");
        // 保存到用户表数据
        foreach($data as $k=>$v) {
            $user = Db::name("vip_user")->where("username",$v["username"])->find();
            //dump($user);die;
            if(empty($user)){
                $re = Db::name("vip_user")->insert(['username'=>$v['username'],'level'=>0,'money'=>$v['sum_money'],'createtime'=>$time,'updatetime'=>$time]);
            } else {
                $re = Db::name("vip_user")->where("id",$user["id"])->setInc("money",$v["sum_money"]);
            }
            if($re !== false){
                //$ids[] = $v["id"];
                // 获取当前等级
                $userMoney = isset($user["sum_money"]) ? $user["sum_money"]+$v["sum_money"] : $v["sum_money"];
                $userLevel = isset($user["level"]) ? $user["level"] : 0;
                $level = $this->level($userMoney,$description);
                // 不相等时晋级
                $this->uplevel($userLevel,$level,$v["username"],$description,$time,$month);
                // 修改归档状态
                Db::name("vip_orders")->where("username",$v["username"])->where("status",0)->where("savetime",$v['savetime'])->update(["status"=>1]);
            }
        }
        $count = count($data);
        //Db::name("vip_orders")->where("id","IN",$ids)->update(['status'=>1]);
        return json(["status"=>200,"msg"=>"保存{$count}条数据成功"]);
    }


    /**
     * 判断当前等级
     */
    public function level($userMoney,$level_money)
    {
        foreach($level_money as $v){
            if($userMoney > $v['save_money']){
                return $v['level'];
            }
        }
        return 0;
    }
    /**
     * 判断是否晋级
     */
    public function uplevel($level,$now_level,$username,$description,$time,$month)
    {
        if($now_level > $level){
            $jiangli = [];
            //$num = $now_level - $level;
            //dump($level);
            //dump($now_level);
            $money = 0;
            for($i = $now_level;$i>$level;$i--){
                foreach($description as $k=>$v){
                    if($i == $v['level']){
                        //$jiangli[$i]["username"] = $username;
                        //$jiangli[$i]["money"] = $v["money"];
                        //$jiangli[$i]["level"] = $v["level"];
                        //$jiangli[$i]["status"] = 0;
                        //$jiangli[$i]["createtime"] = $time;
                        //$jiangli[$i]["month"] = $month;

                        $money += $v["money"];
                        $jiangli["username"] = $username;
                        $jiangli["money"] = $money;
                        $jiangli["level"] = $now_level;
                        $jiangli["status"] = 0;
                        $jiangli["createtime"] = $time;
                        $jiangli["month"] = $month;
                    }
                }
            }
            if(!empty($jiangli)){
                Db::name("vip_user")->where("username",$username)->update(['level'=>$now_level]);
                //dump($jiangli);
                if(Db::name("vip_jiangli")->where("month",$month)->where("username",$username)->count()){
                    Db::name("vip_jiangli")->where("username",$username)->update($jiangli);
                } else {
                    //Db::name("vip_jiangli")->insertAll(array_reverse($jiangli));
                    Db::name("vip_jiangli")->insert($jiangli);
                }
            }
        }
    }




    //=========================================================

    /**
     * 只根据等级发放免费筹码
     * @throws \think\Exception
     */
    public function chouma()
    {
        ini_set("memory_limit","800M");
        set_time_limit(0);

        // 查询时间
        $time = time();
        $month = date("Y-m",$time);

        // 清除上月数据
        Db::name("vip_chouma")->where("month",$month)->delete();

        // 免费筹码
        $description_money = Db::name("vip_description")->order("save_money desc")->select();//奖金
        $chouma_arr = array_column($description_money,"chouma","level");
        //dump($description_money);

        // 合格用户
        $data = Db::name("vip_user")
            ->where("level > 3")
            ->select();
        //dump($data);

        $i = 0;
        $choumaData = [];
        foreach($data as $k=>$v) {
            $i++;
            $level = $v['level'];
            if(isset($chouma_arr["$level"]) && $chouma_arr["$level"] > 0){
                $choumaData[$k]["username"] = $v["username"];
                $choumaData[$k]["month"] = $month;
                $choumaData[$k]["money"] = $chouma_arr["$level"];
                //$choumaData[$k]["status"] = 0;
                $choumaData[$k]["edittime"] = $time;
                if($i > 1000){
                    Db::name("vip_chouma")->insertAll($choumaData);
                    $i = 0;
                    $choumaData = [];
                }
            }
        }
        if(count($choumaData)){
            Db::name("vip_chouma")->insertAll($choumaData);
        }
        $count = count($data);
        echo "ok，发放[{$count}]条数据";

    }

    /**
     * 筹码
     */
    public function chouma_bak()
    {
        ini_set("memory_limit","800M");
        set_time_limit(0);

        // 查询上月有投注的用户
        $time = time();
        $month = date("Y-m",$time);
        $startTime = strtotime(date("Y-m-1",strtotime('last month')));
        $endTime = strtotime(date("Y-m-1",$time));
        //dump(date("Y-m-1",strtotime('last month')));
        //dump(date("Y-m-1",$time));
        //$startTime= strtotime(date("Y-m-1",$time));
        //$endTime = strtotime(date('Y-m-1',strtotime('next month')));
        $data = Db::name("vip_orders")->alias("a")
            ->join("vip_user b","a.username = b.username")
            ->field("a.*,SUM(a.money) AS month_money,b.level")
            ->where("a.savetime >= $startTime AND a.savetime < $endTime")
            ->where("a.status",1)
            ->where("b.level > 0")
            ->group("a.username")
            ->select();
        //dump(Db::name("vip_orders")->getLastSql());
        //dump($data);die;
        $description_money = Db::name("vip_description")->order("save_money desc")->cache(true)->select();//奖金
        foreach($data as $k=>$v) {
            $choumaMoney = $this->chouma_money($v["level"],$v["month_money"],$description_money);
            if($choumaMoney > 0) {
                $choumaData["username"] = $v["username"];
                $choumaData["month"] = $month;
                $choumaData["money"] = $choumaMoney;
                //$choumaData["status"] = 0;
                $choumaData["edittime"] = $time;
                $user = Db::name("vip_chouma")->where("username",$v["username"])->where("month",$month)->find();
                //dump($choumaData);die;
                if(!empty($user)){
                    Db::name("vip_chouma")->where("id",$user["id"])->update($choumaData);
                } else {
                    Db::name("vip_chouma")->insert($choumaData);
                }
            }
        }
        echo "ok";
    }

    /**
     * 查询用户可领取的筹码
     */
    public function chouma_money($userLevel,$userSave_money,$description_money)
    {
        foreach($description_money as $v){
            if($userLevel >= $v["level"] && $userSave_money >= $v["save_money"]){
                return $v["chouma"];
            }
        }
        return 0;
    }


    /**
     * 回滚数据
     */
    public function rollback()
    {
        set_time_limit(0);
        ini_set("memory_limit","800M");
        //$config = ["host"=>"127.0.0.1","port"=>6379];
        //
        ////连接本地的 Redis 服务
        //$redis = new \Redis();
        //$redis->connect($config["host"], $config["port"]);
        //
        //if($redis->lLen($this->rollback) >= 1){
        //    echo "服务器繁忙";
        //    if(!$redis->get($this->rollback2)){
        //        $redis->del($this->rollback);
        //        echo "<br>过期删除list";
        //    }
        //    exit;
        //}



        // 查询VIP等级配置信息
        $levelData = Db::name("vip_description")->order("save_money asc")->cache(true)->select();
        // 回滚数据
        $data = Db::name("vip_orders")->where("status",2)->limit(0,500)->select();
        if(empty($data)){
            return json(["status"=>401,"msg"=>"回滚数据为空"]);
        }
        // 查看是否有数据为归档
        $order_count = Db::name("vip_orders")->where("status",0)->count();
        if($order_count > 0){
            return json(["status"=>401,"msg"=>"请等待,系统正在处理数据"]);
        }

        ////////////
        //$redis->lPush($this->rollback,time());
        //$redis->set($this->rollback2,"过期标识",$this->timeout);

        foreach($data as $k=>$v)
        {
            // 减去用户总金额
            $userData = Db::name("vip_user")->where("username",$v['username'])->find();
            $money = $userData['money'] - $v['money'];
            Db::name("vip_user")->where("username",$v['username'])->setDec("money",$v['money']);
            // 查询是否降级
            $userLevel = $this->slevel($money,$levelData);
            // 删除用户流水记录
            Db::name("vip_orders")->where("id",$v['id'])->delete();
            $userMoney = $userData["money"] - $v['money'];
            Db::name("vip_user")->where("username",$v['username'])->update(["money"=>$userMoney,"level"=>$userLevel]);
            if($userLevel == $userData['level']){
                continue;
            }
            // 删除晋级奖金
            for($i=$userData['level'];$i>$userLevel;$i--) {
                Db::name("vip_jiangli")->where("username",$v['username'])->where("level",$i)->delete();
            }
        }
        $count = count($data);
        return json(["status"=>200,"msg"=>"回滚[{$count}]条数据成功"]);
    }
    /**
     * 判断等级
     */
    public function slevel($num,$levelData)
    {
        $leve = 0;
        foreach($levelData as $v){
            if($num >= $v["save_money"]){
                $leve = $v["level"];
            }
        }
        return $leve;
    }


}
